<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { createOrder } from '../../api/order'
import { getRoomDetail } from '../../api/hotel'
import { createPayment } from '../../api/payment'
import { useUserStore } from '../../store/user'
import { showToast } from 'vant'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const roomId = route.params.roomId as string

// 房间信息
const room = ref<any>({})
// 加载状态
const loading = ref(false)
// 提交订单loading
const submitting = ref(false)

// 日历显示状态
const showCheckInCalendar = ref(false)
const showCheckOutCalendar = ref(false)

// 计算最小日期（今天）
const minDate = new Date()

// 计算日期之间的天数差
const getDaysDiff = (startDate: string, endDate: string) => {
  const start = new Date(startDate)
  const end = new Date(endDate)
  const diffTime = Math.abs(end.getTime() - start.getTime())
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

// 格式化日期为YYYY-MM-DD
const formatDate = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 支付方式选项
const paymentMethods = [
  { name: '线下到店支付', value: '线下到店支付', disabled: false },
  { name: '在线支付', value: '在线支付', disabled: true },
  { name: '微信支付', value: '微信支付', disabled: true }
]

// 订单表单数据
const orderForm = reactive({
  checkInDate: '',
  checkOutDate: '',
  paymentMethod: '线下到店支付',
  nights: 1  // 入住晚数
})

// 获取房间详情
const fetchRoomDetail = async () => {
  try {
    loading.value = true
    const res = await getRoomDetail(roomId)
    room.value = res.data || {}
  } catch (error: any) {
    showToast(error.message || '获取房间详情失败')
  } finally {
    loading.value = false
  }
}

// 选择入住日期
const onSelectCheckInDate = (date: Date) => {
  orderForm.checkInDate = formatDate(date)
  showCheckInCalendar.value = false
  
  // 如果离店日期早于入住日期，则自动设置离店日期为入住日期+1天
  if (!orderForm.checkOutDate || new Date(orderForm.checkOutDate) <= new Date(orderForm.checkInDate)) {
    const nextDay = new Date(date)
    nextDay.setDate(nextDay.getDate() + 1)
    orderForm.checkOutDate = formatDate(nextDay)
  }
  
  // 更新入住晚数
  if (orderForm.checkInDate && orderForm.checkOutDate) {
    orderForm.nights = getDaysDiff(orderForm.checkInDate, orderForm.checkOutDate)
  }
}

// 选择离店日期
const onSelectCheckOutDate = (date: Date) => {
  orderForm.checkOutDate = formatDate(date)
  showCheckOutCalendar.value = false
  
  // 更新入住晚数
  if (orderForm.checkInDate && orderForm.checkOutDate) {
    orderForm.nights = getDaysDiff(orderForm.checkInDate, orderForm.checkOutDate)
  }
}

// 提交订单
const submitOrder = async () => {
  if (!orderForm.checkInDate) {
    return showToast('请选择入住日期')
  }
  if (!orderForm.checkOutDate) {
    return showToast('请选择离店日期')
  }
  
  // 检查入住日期是否小于离店日期
  if (new Date(orderForm.checkInDate) >= new Date(orderForm.checkOutDate)) {
    return showToast('离店日期必须晚于入住日期')
  }
  
  try {
    submitting.value = true
    console.log('userStore', userStore)
    const res = await createOrder({
      userId: Number(userStore.userId),
      roomID: Number(roomId),
      checkInDate: new Date(orderForm.checkInDate).toISOString(),
      checkOutDate: new Date(orderForm.checkOutDate).toISOString()
    })
    
    // 创建支付记录
    if (res.data?.orderID) {
      await createPayment({
        orderID: res.data.orderID,
        amount: room.value.price * orderForm.nights || 0, // 总价 = 单价 * 晚数
        paymentMethod: orderForm.paymentMethod
      })
    }
    
    router.push('/order/success')
  } catch (error: any) {
    // showToast(error.message || '创建订单失败')
    console.log(error)
  } finally {
    submitting.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 页面初始化
onMounted(() => {
  fetchRoomDetail()
  // 设置默认入住日期为今天，离店日期为明天
  const today = new Date()
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)
  
  orderForm.checkInDate = formatDate(today)
  orderForm.checkOutDate = formatDate(tomorrow)
  orderForm.nights = 1 // 默认一晚
})
</script>

<template>
  <div class="order-create-container">
    <van-nav-bar
      title="预订房间"
      left-arrow
      @click-left="goBack"
    />
    
    <div class="loading-container" v-if="loading">
      <van-loading type="spinner" />
    </div>
    
    <template v-else>
      <!-- 房间简介 -->
      <van-cell-group inset class="room-info">
        <van-cell title="酒店名称" :value="room.hotel?.name" />
        <van-cell title="房间类型" :value="room.roomType" />
        <van-cell title="价格" :value="`￥${room.price}/晚`" />
      </van-cell-group>
      
      <!-- 订单信息 -->
      <van-cell-group inset class="order-form">
        <van-cell 
          title="入住日期" 
          is-link 
          :value="orderForm.checkInDate" 
          @click="showCheckInCalendar = true" 
        />
        <van-cell 
          title="离店日期" 
          is-link 
          :value="orderForm.checkOutDate" 
          @click="showCheckOutCalendar = true" 
        />
        <van-cell title="入住天数">
          <template #value>
            <span class="nights-value">{{ orderForm.nights }}晚</span>
          </template>
        </van-cell>
      </van-cell-group>
      
      <!-- 支付方式 -->
      <van-cell-group inset class="payment-method">
        <van-cell title="支付方式" />
        <van-radio-group v-model="orderForm.paymentMethod">
          <van-cell v-for="method in paymentMethods" :key="method.value" :title="method.name" clickable @click="orderForm.paymentMethod = method.disabled ? orderForm.paymentMethod : method.value">
            <template #right-icon>

              <van-radio :name="method.value" :disabled="method.disabled">
                <template v-if="method.disabled">
                  <span class="disabled-text">(暂不可用)</span>
                </template>
                <template v-else>
                  
                  <van-icon name="success" />
                </template>
              </van-radio>
            </template>
          </van-cell>
        </van-radio-group>
      </van-cell-group>
      
      <!-- 提交订单 -->
      <div class="submit-action">
        <div class="total-price">
          总价: <span class="price">￥{{ room.price * orderForm.nights }}</span>
        </div>
        <van-button 
          type="primary" 
          round 
          :loading="submitting"
          @click="submitOrder"
        >
          提交订单
        </van-button>
      </div>
    </template>
    
    <!-- 入住日期日历 -->
    <van-calendar 
      v-model:show="showCheckInCalendar" 
      :min-date="minDate"
      color="#1989fa"
      title="选择入住日期"
      @confirm="onSelectCheckInDate" 
    />
    
    <!-- 离店日期日历 -->
    <van-calendar 
      v-model:show="showCheckOutCalendar" 
      :min-date="new Date(orderForm.checkInDate || minDate)"
      color="#1989fa"
      title="选择离店日期"
      @confirm="onSelectCheckOutDate" 
    />
  </div>
</template>

<style scoped>
.order-create-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 80px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.room-info {
  margin-top: 12px;
}

.order-form {
  margin-top: 12px;
}

.payment-method {
  margin-top: 12px;
}

.disabled-text {
  font-size: 12px;
  color: #999;
  margin-left: 5px;
}

.nights-value {
  color: #1989fa;
  font-weight: bold;
}

.submit-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.total-price {
  font-size: 14px;
}

.price {
  font-size: 18px;
  color: #ee0a24;
  font-weight: bold;
}
</style> 